<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Netty WebSocket Chat</title>
    <style>
        #chat { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; }
        #message { width: 80%; padding: 8px; }
        #send { width: 18%; padding: 8px; }
    </style>
</head>
<body>
<h1>Netty WebSocket Chat</h1>
<div id="chat"></div>
<input type="text" id="message" placeholder="输入消息">
<button id="send">发送</button>

<script>
    const chat = document.getElementById('chat');
    const message = document.getElementById('message');
    const send = document.getElementById('send');

    // 连接WebSocket服务器
    const socket = new WebSocket('ws://localhost:7000/ws');

    // 连接建立时
    socket.onopen = function(e) {
        addMessage('系统', '已连接到聊天服务器');
    };

    // 收到消息时
    socket.onmessage = function(event) {
        const data = JSON.parse(event.data);
        addMessage(data.sender, data.message);
    };

    // 连接关闭时
    socket.onclose = function(event) {
        if (event.wasClean) {
            addMessage('系统', `连接关闭，代码=${event.code} 原因=${event.reason}`);
        } else {
            addMessage('系统', '连接中断');
        }
    };

    // 发送消息
    send.onclick = function() {
        if (message.value) {
            socket.send(JSON.stringify({
                sender: '用户',
                message: message.value
            }));
            message.value = '';
        }
    };

    // 按Enter键发送
    message.onkeypress = function(e) {
        if (e.key === 'Enter') {
            send.click();
        }
    };

    // 添加消息到聊天窗口
    function addMessage(sender, msg) {
        const div = document.createElement('div');
        div.innerHTML = `<strong>${sender}:</strong> ${msg}`;
        chat.appendChild(div);
        chat.scrollTop = chat.scrollHeight;
    }
</script>
</body>
</html>